<template>
  <div class="promotions-management">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        创建活动
      </el-button>
    </div>

    <!-- 活动列表 -->
    <div class="promotions-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="promotion in promotions" :key="promotion.id">
          <div class="promotion-card">
            <div class="promotion-header">
              <h4>{{ promotion.title }}</h4>
              <el-tag :type="getStatusType(promotion.status)">
                {{ getStatusText(promotion.status) }}
              </el-tag>
            </div>
            
            <div class="promotion-content">
              <p class="promotion-desc">{{ promotion.description }}</p>
              <div class="promotion-info">
                <div class="info-item">
                  <span class="label">类型：</span>
                  <span>{{ getTypeText(promotion.type) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">优惠：</span>
                  <span class="discount">{{ formatDiscount(promotion) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">时间：</span>
                  <span>{{ promotion.startTime }} 至 {{ promotion.endTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">使用次数：</span>
                  <span>{{ promotion.usedCount }} / {{ promotion.totalCount || '无限制' }}</span>
                </div>
              </div>
            </div>
            
            <div class="promotion-actions">
              <el-button size="small" @click="editPromotion(promotion)">编辑</el-button>
              <el-button
                size="small"
                :type="promotion.status === 'active' ? 'warning' : 'success'"
                @click="toggleStatus(promotion)"
              >
                {{ promotion.status === 'active' ? '停用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deletePromotion(promotion)">删除</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingPromotion ? '编辑活动' : '创建活动'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="promotionFormRef"
        :model="promotionForm"
        :rules="promotionRules"
        label-width="120px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="promotionForm.title" placeholder="请输入活动标题" />
        </el-form-item>
        
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="promotionForm.type" placeholder="请选择活动类型">
            <el-option label="满减优惠" value="full_reduction" />
            <el-option label="折扣优惠" value="discount" />
            <el-option label="红包优惠" value="coupon" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="promotionForm.type === 'full_reduction'" label="满减设置">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input-number
                v-model="promotionForm.minAmount"
                placeholder="满"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-col>
            <el-col :span="12">
              <el-input-number
                v-model="promotionForm.discountAmount"
                placeholder="减"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item v-if="promotionForm.type === 'discount'" label="折扣设置">
          <el-input-number
            v-model="promotionForm.discountRate"
            placeholder="折扣率"
            :min="0.1"
            :max="1"
            :precision="2"
            style="width: 100%"
          />
          <span style="margin-left: 8px; color: #909399;">例：0.8 表示8折</span>
        </el-form-item>
        
        <el-form-item v-if="promotionForm.type === 'coupon'" label="红包金额">
          <el-input-number
            v-model="promotionForm.couponAmount"
            placeholder="红包金额"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="promotionForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="使用限制">
          <el-input-number
            v-model="promotionForm.totalCount"
            placeholder="总使用次数"
            :min="0"
            style="width: 100%"
          />
          <span style="margin-left: 8px; color: #909399;">0表示无限制</span>
        </el-form-item>
        
        <el-form-item label="活动描述">
          <el-input
            v-model="promotionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="savePromotion" :loading="saving">
          {{ editingPromotion ? '保存修改' : '创建活动' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const showAddDialog = ref(false)
const editingPromotion = ref(null)
const saving = ref(false)
const promotionFormRef = ref()

const promotionForm = reactive({
  title: '',
  type: '',
  minAmount: 0,
  discountAmount: 0,
  discountRate: 0.8,
  couponAmount: 0,
  timeRange: [],
  totalCount: 0,
  description: ''
})

const promotionRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ]
}

// 模拟活动数据
const promotions = ref([
  {
    id: 1,
    title: '满50减10优惠',
    type: 'full_reduction',
    minAmount: 50,
    discountAmount: 10,
    description: '满50元立减10元，限时优惠',
    startTime: '2023-12-01 00:00',
    endTime: '2023-12-31 23:59',
    status: 'active',
    usedCount: 25,
    totalCount: 100
  },
  {
    id: 2,
    title: '新用户8折优惠',
    type: 'discount',
    discountRate: 0.8,
    description: '新用户专享8折优惠',
    startTime: '2023-12-01 00:00',
    endTime: '2023-12-31 23:59',
    status: 'active',
    usedCount: 12,
    totalCount: 50
  },
  {
    id: 3,
    title: '5元红包',
    type: 'coupon',
    couponAmount: 5,
    description: '限时红包，先到先得',
    startTime: '2023-12-01 00:00',
    endTime: '2023-12-15 23:59',
    status: 'expired',
    usedCount: 30,
    totalCount: 30
  }
])

const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'inactive': 'info',
    'expired': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'active': '进行中',
    'inactive': '已停用',
    'expired': '已过期'
  }
  return statusMap[status] || status
}

const getTypeText = (type) => {
  const typeMap = {
    'full_reduction': '满减优惠',
    'discount': '折扣优惠',
    'coupon': '红包优惠'
  }
  return typeMap[type] || type
}

const formatDiscount = (promotion) => {
  switch (promotion.type) {
    case 'full_reduction':
      return `满${promotion.minAmount}减${promotion.discountAmount}`
    case 'discount':
      return `${(promotion.discountRate * 10).toFixed(1)}折`
    case 'coupon':
      return `${promotion.couponAmount}元红包`
    default:
      return ''
  }
}

const editPromotion = (promotion) => {
  editingPromotion.value = promotion
  Object.assign(promotionForm, {
    ...promotion,
    timeRange: [promotion.startTime, promotion.endTime]
  })
  showAddDialog.value = true
}

const savePromotion = async () => {
  if (!promotionFormRef.value) return
  
  try {
    await promotionFormRef.value.validate()
    saving.value = true
    
    // 模拟保存API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const promotionData = {
      ...promotionForm,
      startTime: promotionForm.timeRange[0],
      endTime: promotionForm.timeRange[1],
      status: 'active',
      usedCount: 0
    }
    
    if (editingPromotion.value) {
      // 编辑
      const index = promotions.value.findIndex(p => p.id === editingPromotion.value.id)
      if (index !== -1) {
        promotions.value[index] = { ...promotionData, id: editingPromotion.value.id }
      }
      ElMessage.success('活动修改成功')
    } else {
      // 添加
      promotions.value.push({
        ...promotionData,
        id: Date.now()
      })
      ElMessage.success('活动创建成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const toggleStatus = (promotion) => {
  promotion.status = promotion.status === 'active' ? 'inactive' : 'active'
  ElMessage.success(`活动已${promotion.status === 'active' ? '启用' : '停用'}`)
}

const deletePromotion = async (promotion) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = promotions.value.findIndex(p => p.id === promotion.id)
    if (index !== -1) {
      promotions.value.splice(index, 1)
      ElMessage.success('活动删除成功')
    }
  } catch {
    // 用户取消
  }
}

const resetForm = () => {
  editingPromotion.value = null
  Object.assign(promotionForm, {
    title: '',
    type: '',
    minAmount: 0,
    discountAmount: 0,
    discountRate: 0.8,
    couponAmount: 0,
    timeRange: [],
    totalCount: 0,
    description: ''
  })
  if (promotionFormRef.value) {
    promotionFormRef.value.resetFields()
  }
}

onMounted(() => {
  console.log('Promotions management mounted')
})
</script>

<style lang="scss" scoped>
.promotions-management {
  .action-bar {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .promotions-list {
    .promotion-card {
      background: white;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .promotion-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h4 {
          margin: 0;
          color: #303133;
          font-size: 16px;
        }
      }
      
      .promotion-content {
        .promotion-desc {
          color: #606266;
          font-size: 14px;
          margin-bottom: 16px;
          line-height: 1.5;
        }
        
        .promotion-info {
          .info-item {
            display: flex;
            margin-bottom: 8px;
            font-size: 14px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .label {
              color: #909399;
              width: 60px;
              flex-shrink: 0;
            }
            
            .discount {
              color: #f56c6c;
              font-weight: 600;
            }
          }
        }
      }
      
      .promotion-actions {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        gap: 8px;
        
        .el-button {
          flex: 1;
        }
      }
    }
  }
}
</style> 